package com.hackathon.sgstern;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.TimePickerDialog;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.AutoCompleteTextView;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TimePicker;

import com.google.android.gms.maps.model.LatLng;
import com.hackathon.sgstern.adapter.AddressAutoComplete;
import com.hackathon.sgstern.adapter.SpinnerSportsAdapter;
import com.hackathon.sgstern.dataprovider.DataProvider;
import com.hackathon.sgstern.model.SportEvent;
import com.hackathon.sgstern.model.Sports;
import com.hackathon.sgstern.utilities.AddressUtilities;

public class EventCreation extends Activity {

	EditText title;

	EditText date;

	EditText time;

	EditText minParticipants;

	EditText maxParticipants;

	CheckBox privateBox;

	AutoCompleteTextView addressTextView;

	Spinner spinner;

	private Sports sportType;

	private static Calendar cal;

	private static final SimpleDateFormat dateFormat = new SimpleDateFormat(
			"dd.MM.yyyy", Locale.GERMANY);

	private static final SimpleDateFormat timeFormat = new SimpleDateFormat(
			"HH:mm", Locale.GERMANY);

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_event_creation);

		cal = Calendar.getInstance();
		// Show the Up button in the action bar.

		title = (EditText) findViewById(R.id.creationTitle);

		date = (EditText) findViewById(R.id.creationDate);
		date.setText(dateFormat.format(cal.getTime()));
		date.setFocusable(false);
		date.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				DatePickerFragment newFragment = new DatePickerFragment();
				newFragment.setEditText(date);
				newFragment.show(getFragmentManager(), "datePicker");
			}
		});

		time = (EditText) findViewById(R.id.creationTime);
		time.setText(timeFormat.format(cal.getTime()));
		time.setFocusable(false);
		time.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				TimePickerFragment newFragment = new TimePickerFragment();
				newFragment.setEditText(time);
				newFragment.show(getFragmentManager(), "timePicker");
			}
		});

		addressTextView = (AutoCompleteTextView) findViewById(R.id.creationAddress);
		addressTextView.setAdapter(new AddressAutoComplete(this,
				R.layout.list_item));
		addressTextView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapterView, View view,
					int position, long id) {
				String str = (String) adapterView.getItemAtPosition(position);
				addressTextView.setText(str);
			}
		});
		if (getIntent() != null
				&& getIntent().getExtras() != null
				&& getIntent().getExtras().containsKey(
						SurroundingArea.NEW_EVENT_POSITION_KEY)) {
			addressTextView.setText(getAddressOfPoint());
		}

		spinner = (Spinner) findViewById(R.id.creationSports);
		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				sportType = (Sports) spinner.getSelectedItem();

			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				sportType = Sports.FOOTBALL;
			}
		});

		spinner.setAdapter(new SpinnerSportsAdapter(this));
		minParticipants = (EditText) findViewById(R.id.creationMinParticipants);
		minParticipants.setText("1");
		maxParticipants = (EditText) findViewById(R.id.creationMaxParticipants);
		maxParticipants.setText("20");

		privateBox = (CheckBox) findViewById(R.id.creationPrivate);
		setupActionBar();
	}

	private String getAddressOfPoint() {
		Bundle extras = getIntent().getExtras();
		LatLng position = (LatLng) extras
					.get(SurroundingArea.NEW_EVENT_POSITION_KEY);
		return AddressUtilities.getAddressOfPoint(position, this);
	}

	/**
	 * Set up the {@link android.app.ActionBar}.
	 */
	private void setupActionBar() {

		getActionBar().setDisplayHomeAsUpEnabled(true);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.event_creation, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			// This ID represents the Home or Up button. In the case of this
			// activity, the Up button is shown. Use NavUtils to allow users
			// to navigate up one level in the application structure. For
			// more details, see the Navigation pattern on Android Design:
			//
			// http://developer.android.com/design/patterns/navigation.html#up-vs-back
			//
			NavUtils.navigateUpFromSameTask(this);
			return true;
		case R.id.action_save_new:
			return saveEvent();
		}
		return super.onOptionsItemSelected(item);
	}

	boolean saveEvent() {
		SportEvent sportEvent = new SportEvent();
		sportEvent.title = title.getText().toString();
		sportEvent.time = cal.getTime();
		sportEvent.art = sportType;
		sportEvent.minTeilnehmer = Integer.parseInt(minParticipants.getText()
				.toString());
		sportEvent.maxTeilnehmer = Integer.parseInt(maxParticipants.getText()
				.toString());
		DataProvider.getInstance().addEvent(sportEvent);
		sportEvent.privateEvent = privateBox.isSelected();
		sportEvent.creator = DataProvider.getInstance().getCurrentUser();

		Geocoder geoCoder = new Geocoder(this, Locale.GERMANY);
		try {
			List<Address> addresses = geoCoder.getFromLocationName(
					addressTextView.getText().toString(), 1);
			Address a = addresses.get(0);
			LatLng location = new LatLng(a.getLatitude(), a.getLongitude());
			Log.e("location", location.toString());
			sportEvent.setOrt(location);

		} catch (IOException e) {
			e.printStackTrace();
		}
		NavUtils.navigateUpFromSameTask(this);
		return true;
	}

	@Override
	protected void onStop() {
		date.setText(null);
		time.setText(null);
		title.setText(null);
		cal = null;
		super.onStop();
	}

	public static class DatePickerFragment extends DialogFragment implements
			DatePickerDialog.OnDateSetListener {

		EditText text;

		public DatePickerFragment() {
		}

		@Override
		public Dialog onCreateDialog(Bundle savedInstanceState) {
			// Create a new instance of DatePickerDialog and return it
			return new DatePickerDialog(getActivity(), this,
					cal.get(Calendar.YEAR), cal.get(Calendar.MONTH),
					cal.get(Calendar.DAY_OF_MONTH));
		}

		@Override
		public void onDateSet(DatePicker view, int year, int month, int day) {
			cal.set(Calendar.DAY_OF_MONTH, day);
			cal.set(Calendar.MONTH, month);
			cal.set(Calendar.YEAR, year);
			text.setText(dateFormat.format(cal.getTime()));
		}

		public void setEditText(EditText text) {
			this.text = text;
		}
	}

	public static class TimePickerFragment extends DialogFragment implements
			TimePickerDialog.OnTimeSetListener {

		EditText text;

		public TimePickerFragment() {
		}

		@Override
		public Dialog onCreateDialog(Bundle savedInstanceState) {
			// Create a new instance of DatePickerDialog and return it
			return new TimePickerDialog(getActivity(), this,
					cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE),
					true);
		}

		public void setEditText(EditText text) {
			this.text = text;
		}

		@Override
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			cal.set(Calendar.HOUR_OF_DAY, hourOfDay);
			cal.set(Calendar.MINUTE, minute);
			text.setText(timeFormat.format(cal.getTime()));
		}
	}

}
